package com.cl.ks.flow;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import com.cl.ks.entity.SparkNode;
import com.google.gson.Gson;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class GJ2KS {
    public static void main(String[] args) throws IOException {
        String gj = FileUtils.readFileToString(new File("./gj1.json"), StandardCharsets.UTF_8);
        JSONObject gjObject = JSONObject.parseObject(gj);
        Map<String, SparkNode> nodesMap = new HashMap<>();
        JSONArray nodes = gjObject.getJSONArray("nodes");
        for (int i = 0; i < nodes.size(); i++) {
            SparkNode sparkNode = new SparkNode();
            JSONObject nodeExpression = new JSONObject();
            JSONObject node = nodes.getJSONObject(i);
            String name = node.getString("name");
            String type = node.getString("type");
            String nodeid = node.getString("nodeid");
            sparkNode.setNodeName(name);
            sparkNode.setCode(nodeid);
            if ("DATAELEMENT".equals(type)) {
                String tablename = node.getString("tablename");
                nodeExpression.put("targetTable", tablename);
            }else
            sparkNode.setNodeExpression(nodeExpression);
            nodesMap.put(nodeid, sparkNode);
        }
        JSONArray links = gjObject.getJSONArray("links");
        SparkNode startNode = null;
        // 构建节点之间的连接
        for (int i = 0; i < links.size(); i++) {
            JSONObject link = links.getJSONObject(i);
            String from = (String) link.get("from");
            String to = (String) link.get("to");

            SparkNode fromNode = nodesMap.get(from);
            if (startNode == null) {
                startNode = fromNode;
            }
            SparkNode toNode = nodesMap.get(to);

            if (fromNode.getNextSparkNodes() == null) {
                fromNode.setNextSparkNodes(new ArrayList<>());
            }
            fromNode.getNextSparkNodes().add(toNode);
        }

        JSONObject.toJSONString(startNode, SerializerFeature.DisableCircularReferenceDetect);

        System.out.println();
    }
}
